package com.isoft.mapper;

import com.isoft.entity.DfmeGtlsEntity;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DfmeGtlsMapper {

    @Insert("INSERT INTO MSG_META(SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE) VALUES(#{entity.meta.sender}, #{entity.meta.receiver}, #{entity.meta.sequenceNumber}, TO_TIMESTAMP(#{entity.meta.dateTime}, 'YYYYMMDDHH24MISS'), #{entity.meta.type}, #{entity.meta.subType})")
    @Options(useGeneratedKeys = true, keyProperty = "meta.msgId")
    void insertMeta(@Param("entity") DfmeGtlsEntity entity);

    @Insert("INSERT INTO FLIGHT_BASE(" +
            "FLIGHT_ID, FLIGHT_ATTRIBUTE, FLIGHT_FILE_ID, FLIGHT_IDENTIFIER) " +
            "VALUES(" +
            "#{dflt.flightId,jdbcType=NUMERIC}, " +
            "#{dflt.flightAttribute,jdbcType=VARCHAR}, " +
            "#{dflt.flightFileId,jdbcType=VARCHAR}, " +
            "#{dflt.flightIdentifier,jdbcType=VARCHAR})")
    int insertFlightBase(DfmeGtlsEntity entity);

    @Insert("INSERT INTO GATE(" +
            "GATE_ID, FLIGHT_ID, GATE_NUMBER, GATE_TYPE) " +
            "VALUES(" +
            "SEQ_GATE.nextval, " +
            "#{dflt.flightId,jdbcType=NUMERIC}, " +
            "#{dflt.gtls.gate.code,jdbcType=VARCHAR}, " +
            "SUBSTR(#{dflt.gtls.gate.beltSection,jdbcType=VARCHAR}, 1, 1))")
    int insertGate(DfmeGtlsEntity entity);

    // 修改后的insertBaggageClaim方法，确保BELT_ID有值
    @Insert({
            "<script>",
            "INSERT INTO BAGGAGE_CLAIM(",
            "BELT_ID, FLIGHT_ID, BELT_NUMBER, BELT_CODE, BELT_ATTRIBUTE, ",
            "ESTIMATED_START_TIME, ESTIMATED_END_TIME, REAL_START_TIME, REAL_END_TIME, BELT_SECTION) ",
            "VALUES(",
            "(SELECT COALESCE(MAX(BELT_ID), 0) + 1 FROM BAGGAGE_CLAIM), ", // 手动生成ID
            "#{dflt.flightId,jdbcType=NUMERIC}, ",
            "#{dflt.gtls.gate.gateNumber,jdbcType=VARCHAR}, ",
            "#{dflt.gtls.gate.code,jdbcType=VARCHAR}, ",
            "#{dflt.gtls.gate.gateAttribute,jdbcType=VARCHAR}, ",
            "TO_TIMESTAMP(#{dflt.gtls.gate.estimatedStartTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'), ",
            "TO_TIMESTAMP(#{dflt.gtls.gate.estimatedEndTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'), ",
            "TO_TIMESTAMP(#{dflt.gtls.gate.realStartTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'), ",
            "TO_TIMESTAMP(#{dflt.gtls.gate.realEndTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'), ",
            "#{dflt.gtls.gate.beltSection,jdbcType=VARCHAR})",
            "</script>"
    })
    int insertBaggageClaim(DfmeGtlsEntity entity);

    @Select("SELECT COUNT(1) FROM FLIGHT_BASE WHERE FLIGHT_ID = #{flightId,jdbcType=NUMERIC}")
    int countFlightById(@Param("flightId") Long flightId);
}